﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Logging;
using VAdvantage.Controls;
using VAdvantage.Utility;
using System.Data;
using VAdvantage.Model;
using VAdvantage.DataBase;
using VAdvantage.Classes;
using System.Text;

namespace VAdvantage.Search
{
    public partial class InfoPAttribute : ChildWindow
    {

        #region Private variable
        private static long serialVersionUID = 1L;
        //	Resulting Query			
        private string _query = "";
        //	Product Attribure Editors	
        private List<Control> m_productEditors = new List<Control>();
        private List<Control> m_productEditorsTo = new List<Control>();
        //	Instance Attribute Editors	
        private List<Control> m_instanceEditors = new List<Control>();
        private List<Control> m_instanceEditorsTo = new List<Control>();
        //	Logger			
        private static VLogger log = VLogger.GetVLogger(typeof(InfoPAttribute).FullName);
        private System.ComponentModel.IContainer components;
        private ToolTip _wndToolTip;

        // Fixed Controls
        Label lblSerialNo = new Label();
        Label lblLotNo = new Label();
        Label lblLot = new Label();
        VDatePicker dtpGuaranteeDateField = new VDatePicker(); 
        VComboBox cmbGuaranteeDateSelection = new VComboBox();
        VComboBox cmbLot = new VComboBox();
        VTextBox txtSerialNo = new VTextBox();
        VTextBox txtLotNo = new VTextBox();
        InfoProduct pro = null;

        #endregion

        /// <summary>
        /// Default Constructor
        /// </summary>
        public InfoPAttribute()
        {
            InitializeComponent();
            this.Title = Msg.GetMsg(Envs.GetCtx(), "InfoPAttribute");
        }

        /// <summary>
        /// Constructor.
        /// Called from InfoProduct,cmd_InfoPAttribute
        /// </summary>
        /// <param name="parent">parent</param>
        public InfoPAttribute(ContentControl parent)
            : this()
        {
            
            try
            {
                pro = (InfoProduct)parent;
                _wndToolTip = new ToolTip();
                //tblpTop.RowCount = 0;
                Init();
                DynInit();
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, "InfoPAttribute", e);
            }

        }

        /// <summary>
        /// Static Init
        /// </summary>
        private void Init()
        {
            lblSerialNo.Content = Msg.Translate(Envs.GetCtx(), "SerNo");
            lblLotNo.Content = Msg.Translate(Envs.GetCtx(), "Lot");
            lblLot.Content = Msg.Translate(Envs.GetCtx(), "M_Lot_ID");
        }

        /// <summary>
        /// Dynamic Init of the Center Panel
        /// </summary>
        private void DynInit()
        {
            int row = AddAttributes();
        }

        /// <summary>
        /// Add Attributes
        /// </summary>
        /// <returns>rows</returns>
        private int AddAttributes()
        {
            int row = 0;
            KeyNamePair[] itemCom;
            IDataReader idr = null;
            String sql = MRole.GetDefault().AddAccessSQL(
                "SELECT M_Attribute_ID, Name, Description, AttributeValueType, IsInstanceAttribute "
                + "FROM M_Attribute "
                + "WHERE IsActive='Y' "
                + "ORDER BY IsInstanceAttribute, Name",
                "M_Attribute", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
            try
            {
                bool instanceLine = false;
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                 {
                     idr = DB.ExecuteReader(sql);
                     itemCom = InitLotSelection();

                     while (idr.Read())
                     {
                         int attribute_ID = Util.GetValueOfInt(idr[0]);
                         String name = Util.GetValueOfString(idr[1]);
                         String description = Util.GetValueOfString(idr[2]);
                         String attributeValueType = Util.GetValueOfString(idr[3]);
                         bool isInstanceAttribute = "Y".Equals(Util.GetValueOfString(idr[4]));
                         KeyNamePair[] pair = GetAttributeList(attribute_ID);
                         bool fetching = true;
                         Dispatcher.BeginInvoke(delegate
                          {
                              //	Instance switch
                              if (!instanceLine && isInstanceAttribute)
                              {
                                  Label group = new Label();
                                  group.Content = Msg.Translate(Envs.GetCtx(), "IsInstanceAttribute") + "     ";
                                  Grid.SetColumnSpan(group, 2);
                                  //tblpTop.Controls.Add(group, 0, row++);
                                  tblpTop.Children.Add(group);
                                  Grid.SetColumn(group, 0);
                                  Grid.SetRow(group, row++);
                                  group.Margin = new Thickness(2);

                                  instanceLine = true;
                                  //tblpTop.RowCount++;
                                  tblpTop.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                              }
                              //
                              Label label = new Label();
                              label.Content = name;

                              if (description != null && description.Length > 0)
                              {
                                  //_wndToolTip.SetToolTip(label, description);
                              }
                              // tblpTop.RowCount++;
                              tblpTop.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                              //add lavel in the table
                              //label.Anchor = AnchorStyles.Right;
                              //label.AutoSize = true;
                              //tblpTop.Controls.Add(label, 0, row++);
                              tblpTop.Children.Add(label);
                              Grid.SetColumn(label, 0);
                              Grid.SetRow(label, row++);
                              label.Margin = new Thickness(2);

                              //Control field = null;
                              Control field = null;
                              if (X_M_Attribute.ATTRIBUTEVALUETYPE_List.Equals(attributeValueType))
                              {
                                  field = new VComboBox(pair);
                              }
                              else if (X_M_Attribute.ATTRIBUTEVALUETYPE_Number.Equals(attributeValueType))
                              {
                                  field = new VNumTextBox(name, false, false, true, DisplayType.Number, name);
                              }
                              else
                              {
                                  field = new VTextBox(name, false, false, true, 10, 40, null, null);
                              }
                              //label.Name = field;


                              /************  start Add control to end of list*******/
                              int rowCount = tblpTop.RowDefinitions.Count;
                              if (rowCount == -1)
                              {
                                  //tblpTop.RowCount = 0;
                                  // tblpTop.RowDefinitions = null;
                              }
                              int col = 1;// tblpTop.Controls.Count + 1;// getMaxCol(row) + 1;
                              // centerPanel.add(field, null);
                              if (rowCount >= 0)
                              {
                                  rowCount = rowCount - 1;
                              }
                              RunTimeDesign(field);
                              // tblpTop.Controls.Add(field, col, rowCount);
                              tblpTop.Children.Add(field);
                              Grid.SetColumn(field, col);
                              Grid.SetRow(field, rowCount);
                              field.Margin = new Thickness(2);

                              /************ End start Add control to end of list*******/
                              //
                              field.Name = Util.GetValueOfString(attribute_ID);
                              if (isInstanceAttribute)
                              {
                                  m_instanceEditors.Add(field);
                              }
                              else
                              {
                                  m_productEditors.Add(field);
                              }

                              //	To (numbers)
                              Control fieldTo = null;
                              if (X_M_Attribute.ATTRIBUTEVALUETYPE_Number.Equals(attributeValueType))
                              {
                                  fieldTo = new VNumTextBox(name, false, false, true, DisplayType.Number, name);

                                  //tblpTop.Controls.Add(new Label("-"), null);
                                  //RunTimeDesign(fieldTo);
                                  //tblpTop.Controls.Add(fieldTo, null);
                              }
                              if (isInstanceAttribute)
                              {
                                  m_instanceEditorsTo.Add(fieldTo);
                              }
                              else
                              {
                                  m_productEditorsTo.Add(fieldTo);
                              }
                              fetching = false;
                          });
                         while (fetching)
                         {
                             System.Threading.Thread.Sleep(1);
                         }
                     }
                     idr.Close();

                     Dispatcher.BeginInvoke(delegate
                         {
                             //DynaInit
                             String s = Msg.Translate(Envs.GetContext(), "GuaranteeDate");

                             cmbGuaranteeDateSelection.Items.Add(s + " <");
                             cmbGuaranteeDateSelection.Items.Add(s + " =");
                             cmbGuaranteeDateSelection.Items.Add(s + " >");

                             cmbLot = new VComboBox(itemCom);

                             //tblpTop.RowCount++;
                             tblpTop.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                             //	Fixed Instance Selection Fields	

                             //tblpTop.Controls.Add(lblSerialNo, 0, row);
                             tblpTop.Children.Add(lblSerialNo);
                             Grid.SetColumn(lblSerialNo, 0);
                             Grid.SetRow(lblSerialNo, row);
                             lblSerialNo.Margin = new Thickness(2);

                             RunTimeDesign(txtSerialNo);
                             //tblpTop.Controls.Add(txtSerialNo, 1, row++);
                             tblpTop.Children.Add(txtSerialNo);
                             Grid.SetColumn(txtSerialNo, 1);
                             Grid.SetRow(txtSerialNo, row++);
                             txtSerialNo.Margin = new Thickness(2);

                             //tblpTop.RowCount++;
                             tblpTop.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                             //tblpTop.Controls.Add(lblLot, 0, row);
                             tblpTop.Children.Add(lblLot);
                             Grid.SetColumn(lblLot, 0);
                             Grid.SetRow(lblLot, row);
                             lblLot.Margin = new Thickness(2);

                             RunTimeDesign(cmbLot);
                             // tblpTop.Controls.Add(cmbLot, 1, row++);
                             tblpTop.Children.Add(cmbLot);
                             Grid.SetColumn(cmbLot, 1);
                             Grid.SetRow(cmbLot, row++);
                             cmbLot.Margin = new Thickness(2);

                             //tblpTop.RowCount++;
                             tblpTop.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                             //tblpTop.Controls.Add(lblLotNo, 0, row);
                             tblpTop.Children.Add(lblLotNo);
                             Grid.SetColumn(lblLotNo, 0);
                             Grid.SetRow(lblLotNo, row);
                             lblLotNo.Margin = new Thickness(2);

                             RunTimeDesign(txtLotNo);
                             //tblpTop.Controls.Add(txtLotNo, 1, row++);//lotSelection
                             tblpTop.Children.Add(txtLotNo);
                             Grid.SetColumn(txtLotNo, 1);
                             Grid.SetRow(txtLotNo, row++);
                             txtLotNo.Margin = new Thickness(2);

                             //tblpTop.RowCount++;
                             tblpTop.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

                             cmbGuaranteeDateSelection.Width = 100;
                             // tblpTop.Controls.Add(cmbGuaranteeDateSelection, 0, row);
                             tblpTop.Children.Add(cmbGuaranteeDateSelection);
                             Grid.SetColumn(cmbGuaranteeDateSelection, 0);
                             Grid.SetRow(cmbGuaranteeDateSelection, row);
                             cmbGuaranteeDateSelection.Margin = new Thickness(2);

                             RunTimeDesign(dtpGuaranteeDateField);
                             // tblpTop.Controls.Add(dtpGuaranteeDateField, 1, row++);
                             tblpTop.Children.Add(dtpGuaranteeDateField);
                             Grid.SetColumn(dtpGuaranteeDateField, 1);
                             Grid.SetRow(dtpGuaranteeDateField, row++);
                             dtpGuaranteeDateField.Margin = new Thickness(2);
                             Show();
                         });

                 });

            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql, e);
                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }
            }
            return row;
        }

        /// <summary>
        /// Get Attribute List
        /// </summary>
        /// <param name="M_Attribute_ID">attribure</param>
        /// <returns>array</returns>
        private KeyNamePair[] GetAttributeList(int M_Attribute_ID)
        {
            List<KeyNamePair> list = new List<KeyNamePair>();
            list.Add(new KeyNamePair(-1, ""));

            IDataReader idr = null;
            String sql = MRole.GetDefault().AddAccessSQL(
                "SELECT M_AttributeValue_ID, Value, Name "
                + " FROM M_AttributeValue "
                + " WHERE M_Attribute_ID= " + M_Attribute_ID
                + " ORDER BY 2",
                " M_AttributeValue", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
            try
            {
                idr = DB.ExecuteReader(sql);
                while (idr.Read())
                {
                    list.Add(new KeyNamePair(Util.GetValueOfString(idr[0]), Util.GetValueOfString(idr[2])));
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }

                log.Log(Level.SEVERE, sql, e);
            }
            KeyNamePair[] retValue = new KeyNamePair[list.Count];
            retValue = list.ToArray();
            return retValue;
        }

        /// <summary>
        /// Initialize Lot Selection
        /// </summary>
        private KeyNamePair[] InitLotSelection()
        {
            List<KeyNamePair> list = new List<KeyNamePair>();
            list.Add(new KeyNamePair(-1, ""));
            String sql = MRole.GetDefault().AddAccessSQL(
                "SELECT M_Lot_ID, Name FROM M_Lot WHERE IsActive='Y' ORDER BY 2",
                "M_Lot", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
            IDataReader idr = null;
            try
            {
                idr = DB.ExecuteReader(sql);
                while (idr.Read())
                {
                    list.Add(new KeyNamePair(Util.GetValueOfInt(idr[0]), Util.GetValueOfString(idr[1])));
                }
                idr.Close();
            }
            catch (Exception e)
            {
                log.Log(Level.SEVERE, sql, e);
                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }
            }

            //	Create List
            KeyNamePair[] items = new KeyNamePair[list.Count];
            items = list.ToArray();
            return items;
            //combo fill
            //cmbLot = new VComboBox(items);
        }

        /// <summary>
        /// Create Query
        ///  <code>
        ///  Available synonyms:
        ///  M_Product p
        ///  M_ProductPrice pr
        ///  M_AttributeSet pa
        ///  </code>
        /// </summary>
        /// <returns>query</returns>
        private String CreateQuery()
        {
            /***	Instance Attributes		*/
            StringBuilder sb = new StringBuilder();
            //	Serial No
            String s = txtSerialNo.GetText();
            if (s != null && s.Length > 0)
            {
                sb.Append(" AND asi.SerNo");
                if (s.IndexOf('%') == -1 && s.IndexOf('_') == 1)
                    sb.Append("=");
                else
                    sb.Append(" LIKE ");
                sb.Append(DataBase.DB.TO_STRING(s));
            }
            //	Lot Number
            s = txtLotNo.GetText();
            if (s != null && s.Length > 0)
            {
                sb.Append(" AND asi.Lot");
                if (s.IndexOf('%') == -1 && s.IndexOf('_') == 1)
                    sb.Append("=");
                else
                    sb.Append(" LIKE ");
                sb.Append(DataBase.DB.TO_STRING(s));
            }
            //	Lot ID
            KeyNamePair pp = (KeyNamePair)cmbLot.SelectedItem;
            if (pp != null && pp.GetKey() != -1)
            {
                int ID = pp.GetKey();
                sb.Append(" AND asi.M_Lot_ID=").Append(ID);
            }

            //	Guarantee Date
            DateTime? ts = (DateTime?)dtpGuaranteeDateField.GetValue();
            if (ts != null)
            {
                sb.Append(" AND TRUNC(asi.GuaranteeDate,'DD')");
                int index = cmbGuaranteeDateSelection.SelectedIndex;	//	 < = >
                if (index == 0)
                    sb.Append("<");
                else if (index == 1)
                    sb.Append("=");
                else
                    sb.Append(">");
                sb.Append(DataBase.DB.TO_DATE(ts, true));
            }
            try
            {

                //	Instance Editors
                for (int i = 0; i < m_instanceEditors.Count; i++)
                {
                    StringBuilder iAttr = new StringBuilder();
                    Control c = (Control)m_instanceEditors[i];
                    Control cTo = (Control)m_instanceEditorsTo[i];

                    //int M_Attribute_ID = int.Parse(c.getName());
                    int M_Attribute_ID = Util.GetValueOfInt(c.Name);
                    if (c is VComboBox)
                    {
                        VComboBox field = (VComboBox)c;
                        pp = (KeyNamePair)field.SelectedItem;
                        if (pp != null && pp.GetKey() != -1)
                        {
                            iAttr.Append("M_Attribute_ID=").Append(M_Attribute_ID)
                                .Append(" AND M_AttributeValue_ID=").Append(pp.GetKey());
                        }
                    }
                    else if (c is VNumTextBox)
                    {
                        VNumTextBox field = (VNumTextBox)c;
                        Decimal value = (Decimal)field.GetValue();
                        VNumTextBox fieldTo = (VNumTextBox)cTo;
                        Decimal valueTo = (Decimal)fieldTo.GetValue();
                        if (value != null || valueTo != null)
                        {
                            iAttr.Append("M_Attribute_ID=").Append(M_Attribute_ID)
                                .Append(" AND ValueNumber");
                            if (value != null && valueTo == null)
                                iAttr.Append("=").Append(value);
                            else if (value == null && valueTo != null)
                                iAttr.Append("<=").Append(valueTo);
                            else if (value != null && valueTo != null)
                                iAttr.Append(" BETWEEN ").Append(value)
                                    .Append(" AND ").Append(valueTo);
                        }
                    }
                    else
                    {
                        VTextBox field = (VTextBox)c;
                        String value = field.GetText();
                        if (value != null && value.Length > 0)
                        {
                            iAttr.Append("M_Attribute_ID=").Append(M_Attribute_ID)
                                .Append(" AND Value");
                            if (value.IndexOf('%') == -1 && value.IndexOf('_') == -1)
                                iAttr.Append("=");
                            else
                                iAttr.Append(" LIKE ");
                            iAttr.Append(DataBase.DB.TO_STRING(value));
                        }
                    }
                    //	Add to where
                    if (iAttr.Length > 0)
                        sb.Append(" AND asi.M_AttributeSetInstance_ID IN "
                            + "(SELECT M_AttributeSetInstance_ID FROM M_AttributeInstance "
                            + "WHERE ")
                            .Append(iAttr).Append(")");
                }

            }
            catch
            { }

            //	finish Instance Attributes
            if (sb.Length > 0)
            {
                sb.Insert(0, " AND EXISTS (SELECT * FROM M_Storage s"
                    + " INNER JOIN M_AttributeSetInstance asi ON (s.M_AttributeSetInstance_ID=asi.M_AttributeSetInstance_ID) "
                    + "WHERE s.M_Product_ID=p.M_Product_ID");
                sb.Append(")");
            }


            //	Product Attributes 
            for (int i = 0; i < m_productEditors.Count; i++)
            {
                StringBuilder pAttr = new StringBuilder();
                Control c = (Control)m_productEditors[i];
                Control cTo = (Control)m_productEditorsTo[i];
                int M_Attribute_ID = Util.GetValueOfInt(c.Name);//c.getName());
                if (c is VComboBox)
                {
                    VComboBox field = (VComboBox)c;
                    pp = (KeyNamePair)field.SelectedItem;
                    if (pp != null && pp.GetKey() != -1)
                    {
                        pAttr.Append("M_Attribute_ID=").Append(M_Attribute_ID)
                            .Append(" AND M_AttributeValue_ID=").Append(pp.GetKeyID());
                    }
                }
                else if (c is VNumTextBox)
                {
                    VNumTextBox field = (VNumTextBox)c;
                    Decimal value = (Decimal)field.GetValue();
                    VNumTextBox fieldTo = (VNumTextBox)cTo;
                    Decimal valueTo = (Decimal)fieldTo.GetValue();
                    if (value != null || valueTo != null)
                    {
                        pAttr.Append("M_Attribute_ID=").Append(M_Attribute_ID)
                            .Append(" AND ValueNumber");
                        if (value != null && valueTo == null)
                            pAttr.Append("=").Append(value);
                        else if (value == null && valueTo != null)
                            pAttr.Append("<=").Append(valueTo);
                        else if (value != null && valueTo != null)
                            pAttr.Append(" BETWEEN ").Append(value)
                                .Append(" AND ").Append(valueTo);
                    }
                }
                else
                {
                    VTextBox field = (VTextBox)c;
                    String value = field.GetText();
                    if (value != null && value.Length > 0)
                    {
                        pAttr.Append("M_Attribute_ID=").Append(M_Attribute_ID)
                            .Append(" AND Value");
                        if (value.IndexOf('%') == -1 && value.IndexOf('_') == -1)
                            pAttr.Append("=");
                        else
                            pAttr.Append(" LIKE ");
                        pAttr.Append(DataBase.DB.TO_STRING(value));
                    }
                }
                //	Add to Where
                if (pAttr.Length > 0)
                {
                    sb.Append(" AND p.M_AttributeSetInstance_ID IN "
                        + "(SELECT M_AttributeSetInstance_ID "
                        + "FROM M_AttributeInstance WHERE ")
                           .Append(pAttr).Append(")");
                }
            }
            _query = null;
            if (sb.Length > 0)
            {
                _query = sb.ToString();
            }
            log.Config(_query);
            return _query;
        }

        private void RunTimeDesign(Control ctrl)
        {
            //ctrl.Anchor = ((AnchorStyles)((AnchorStyles.Left | AnchorStyles.Right)));
            // ctrl.Size = new System.Drawing.Size(221, 21);
        }

        /// <summary>
        /// Get resulting Query WHERE
        /// </summary>
        /// <returns>query or null</returns>
        public String GetWhereClause()
        {
            return _query;
        }


        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            string query = CreateQuery();
            this.DialogResult = true;
            pro.RunAttributeQuery(query);
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            _query = null;
            this.DialogResult = false;
        }

        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void SetBusy(bool isBusy)
        {
            busyWindow.Visibility = isBusy ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtBusy.Visibility = isBusy ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }
    }
}

